package com.gaofans.vertx.boot.dbutils.mapper.rows;

import com.gaofans.vertx.boot.dbutils.mapper.BeanProcessor;
import com.gaofans.vertx.boot.dbutils.mapper.ColumnMapper;
import com.gaofans.vertx.boot.dbutils.mapper.RowMapper;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

public class ScalarRowMapper<T> implements RowMapper<T> {

    private Class<T> type;

    @Override
    public void setType(final Class<T> type) {
        this.type = type;
    }

    @Override
    @SuppressWarnings("all")
    public T single(RowSet<Row> rs) {
        Assert.notNull(this.type,"未指定类型");
        Row row = rs.iterator().next();
        for (ColumnMapper mapper : BeanProcessor.mappers) {
            if(mapper.match(this.type)){
                return (T) mapper.apply(row,row.getColumnName(0));
            }
        }
        return null;
    }

    @Override
    @SuppressWarnings("all")
    public List<T> list(RowSet<Row> rs) {
        Assert.notNull(this.type,"未指定类型");
        List<T> result = new ArrayList<>();
        for (Row row : rs) {
            for (ColumnMapper mapper : BeanProcessor.mappers) {
                if(mapper.match(this.type)){
                    result.add((T) mapper.apply(row,row.getColumnName(0)));
                }
            }
        }
        return result;
    }
}
